package com.talkyun.utils.revised.http;

import java.io.IOException;
import java.lang.reflect.Constructor;

/**
 * Created by daibing on 2020/12/8
 */
public class HttpConnectorFactory {
    private Constructor connectorConstructor;

    public HttpConnector getConnector(String url) throws IOException {
        return this.getConnector(url, 3000);
    }

    public HttpConnector getConnector(String url, int timeout) {
        if (connectorConstructor == null) {
            Class<?> clazz = this.getConnectorClazz();
            try {
                connectorConstructor = clazz.getConstructor(String.class, int.class, boolean.class);
            } catch (NoSuchMethodException e) {
                throw new RuntimeException(e);
            }
        }

        try {
            return (HttpConnector) connectorConstructor.newInstance(url, timeout, true);
        } catch (Exception e) {
            throw new RuntimeException("Can't build new instance!", e);
        }
    }

    private Class<?> getConnectorClazz() {
        String clazz = System.getProperty("http.connector");
        if (clazz == null || clazz.trim().length() == 0) {
            return HttpConnector.class;
        }

        try {
            return Class.forName(clazz);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}
